package nccloud.riart.bs.bgplugin;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.NCLocator;
import nc.bs.pub.pa.PreAlertObject;
import nc.bs.pub.taskcenter.BgWorkingContext;
import nc.bs.pub.taskcenter.IBackgroundWorkPlugin;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.am.common.util.CollectionUtils;
import nc.vo.pf.worknote.WorkNoteVO;
import nc.vo.pub.BusinessException;
import nccloud.riart.pub.utils.OAHttpClientUtils;

/**
 * 用于补偿由于不可抗拒因素导致审批流程不统一的单据做再一次OA已办请求
 * 
 * @author Lenovo
 *
 */
public class CompensationPaidBgPlugin implements IBackgroundWorkPlugin {

	// 调用NCC系统单点登录系统的基础URL
	private BaseDAO dao = new BaseDAO();

	@Override
	public PreAlertObject executeTask(BgWorkingContext arg0) throws BusinessException {
		// 查询未同步的异常审批工作
		List<WorkNoteVO> unSynBills = this.getUnSynBill();

		if (CollectionUtils.isNotEmpty(unSynBills)) {
			try {
				for (WorkNoteVO workNoteVO : unSynBills) {
					// 转为请求OA接口的数据格式
					String postData = this.synApproveBillsToRequestModel(workNoteVO);
					nc.bs.logging.Logger.error("CompensationPaidBgPlugin ----- 开始请求OA接口");
					// 请求接口获取返回结果
					String result = OAHttpClientUtils.reqOA_Task("requestDoneUrl", postData);
					nc.bs.logging.Logger.error("请求OA更新已办接口返回成功：" + result);
					// 同步更新消息状态
					if(result!=null) {
						JSONObject retjson = (JSONObject) JSONObject.parse(result);
						String res = retjson.getString("result");
						this.synNCCBills(workNoteVO, res);
					}
				}
			} catch (Exception e) {
				nc.bs.logging.Logger.error("CompensationPaidBgPlugin");
				nc.bs.logging.Logger.error(e);
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 查询异常审批流消
	 * 
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	private List<WorkNoteVO> getUnSynBill() throws BusinessException {
		IUAPQueryBS queryService = NCLocator.getInstance().lookup(IUAPQueryBS.class);
		// 20210328 补充完成待办的条
		String queryWorkNoteSql = "select * from pub_workflownote where (approveresult = 'Y' and approvestatus = '4' and userObject <> '已同步') or (approvestatus = '1' and userObject <> '已同步') or (approvestatus = '4' and userObject = '驳回');";
		List<WorkNoteVO> unapproveBillList = (List<WorkNoteVO>) queryService.executeQuery(queryWorkNoteSql,
				new BeanListProcessor(WorkNoteVO.class));
		return unapproveBillList;
	}

	/**
	 * 待办消息转为请求OA系统的VO数据
	 * 
	 * @param workNoteVO
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private String synApproveBillsToRequestModel(WorkNoteVO workNoteVO) throws Exception {
		String sendJson = null;
		BaseDAO baseDao = new BaseDAO();
		if (null != workNoteVO) {
			String querySql = "select ap.billid, ap.pk_message, ap.msgsourcetype,ap.subject, ap.sendtime, bt.billtypename, rp.appcode, rp.pagecode "
					+ "from sm_msg_approve ap, bd_billtype bt, bd_relatedapp rp " + "where ap.pk_detail = '"
					+ workNoteVO.getPk_checkflow()
					+ "' and bt.pk_billtypecode = ap.billtype and rp.pk_billtypecode = bt.parentbilltype "
					+ "and ( nvl ( rp.dr, 0 ) = 0 ) and rp.sence = 3";
			Map<String, String> resultMap = (Map<String, String>) baseDao.executeQuery(querySql, new MapProcessor());
			// 如果根据父编码查询为空，则再根据编码自身查询一次
			if (null == resultMap || resultMap.size() == 0) {
				querySql = "select ap.billid, ap.pk_message, ap.msgsourcetype,ap.subject, ap.sendtime, bt.billtypename, rp.appcode, rp.pagecode "
						+ "from sm_msg_approve ap, bd_billtype bt, bd_relatedapp rp " + "where ap.pk_detail = '"
						+ workNoteVO.getPk_checkflow()
						+ "' and bt.pk_billtypecode = ap.billtype and rp.pk_billtypecode = bt.pk_billtypecode "
						+ "and ( nvl ( rp.dr, 0 ) = 0 ) and rp.sence = 3";
				resultMap = (Map<String, String>) baseDao.executeQuery(querySql, new MapProcessor());
			}
			if (null != resultMap && resultMap.size() > 0) {
				sendJson = this.generateSendData(workNoteVO, resultMap);
			}
		}
		return sendJson;
	}

	/**
	 * 拼接及赋值
	 * 
	 * @param requestModel
	 * @param workNoteVO
	 * @param resultMap
	 * @throws Exception
	 */
	private String generateSendData(WorkNoteVO workNoteVO, Map<String, String> resultMap)
			throws Exception {
		String pk_message = resultMap.get("pk_message");
//		JSONObject jsobj = new JSONObject();
//	    jsobj.put("WrkID", pk_message);//消息主键
//		return jsobj.toJSONString();
		String urlData = "";
		urlData += "WrkID=" + pk_message;
		return urlData;
	}

	/**
	 * 更新消息状态
	 * @param workNoteVO
	 * @param returnState
	 * @throws BusinessException
	 */
	private void synNCCBills(WorkNoteVO workNoteVO, String result) throws BusinessException {
		if (null != workNoteVO && "success".equals(result)) {
			String pk_checkflow = workNoteVO.getPk_checkflow();
			String updatesql = "update pub_workflownote set userObject = '已同步'  where pk_checkflow = '" + pk_checkflow + "'";
			dao.executeUpdate(updatesql);
		}
	}
}
